<template>
  <div class="app-container">
    <el-form :inline="true" :model="listQuery" @submit.native.prevent>
      <el-form-item label="标题">
        <el-input v-model="listQuery.q_title" maxlength="20" style="width: 200px;" size="small" class="filter-item" />
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="listQuery.q_status" size="small" placeholder="请选择">
          <el-option v-for="item in floorStatus" :label="item.name" :key="item.value" :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="日期">
        <el-date-picker v-model="listQuery.q_time" type="datetime" placeholder="选择日期时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-search" size="small" type="primary" @click="check">查询</el-button>
        <el-button icon="el-icon-refresh" size="small" @click="reset">重置</el-button>
      </el-form-item>
    </el-form>
    <div class="button-table-margin">
      <el-button size="small" type="primary" @click="addBanner" v-permission="['admin/mindex/banner/create']">添加
      </el-button>
      <el-button size="small" type="primary" @click="editBanner" v-permission="['admin/mindex/banner/update']">修改
      </el-button>
      <el-button size="small" type="primary" @click="del" v-permission="['admin/mindex/banner/delete']">删除</el-button>
      <el-button size="small" type="primary" @click="up" v-permission="['admin/mindex/banner/up']">启用</el-button>
      <el-button size="small" type="primary" @click="down" v-permission="['admin/mindex/banner/down']">停用</el-button>
    </div>
    <el-table ref="singleTable" :data="dataList" v-loading="listLoading" border fit highlight-current-row
      style="width: 100%" max-height="450" @current-change="handleCurrentChange">
      <el-table-column type="index" align="center" width="50">
      </el-table-column>
      <el-table-column width="200" label="图片">
        <template slot-scope="scope">
          <img style='height: 80px;' :src="$imagePath+scope.row.image"></img>
        </template>
      </el-table-column>
      <el-table-column property="title" width="200" label="标题" show-overflow-tooltip>
      </el-table-column>
      <el-table-column property="linkUrl" width="200" label="链接地址" show-overflow-tooltip>
      </el-table-column>
      <el-table-column property="startTime" width="200" label="开始时间">
      </el-table-column>
      <el-table-column property="endTime" width="200" label="结束时间">
      </el-table-column>
      <el-table-column label="使用状态">
        <template slot-scope="scope">
          {{ codeBox.USE_YN[scope.row.status] }}
        </template>
      </el-table-column>
      <el-table-column property="orderNo" label="排序号">
      </el-table-column>
      <el-table-column property="updateUserName" label="修改人">
      </el-table-column>
      <el-table-column property="updateTime" width="200" label="修改时间">
      </el-table-column>
      <el-table-column property="createUserName" label="创建人">
      </el-table-column>
      <el-table-column property="updateTime" width="200" label="创建时间">
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit"
      @pagination="getList" />
    <el-dialog :title="judgmentTitle" :visible.sync="dialogFormVisible" width="70%">
      <div class="app-container">
        <el-row>
          <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" label-position="right"
            class="demo-ruleForm  el-form-bottom">
            <el-col :span="24">
              <el-form-item label="标题" prop="title">
                <el-input v-model="ruleForm.title" style="width: 296.66px"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="链接地址" prop="linkUrl">
                <el-input v-model="ruleForm.linkUrl" style="width: 296.66px"></el-input>
                <span class="form-word-hint">请填写完整的地址,例如:http://www.xxx.com/product/1.html</span>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="图片" prop="image">
                <el-upload class="avatar-uploader" :action="$imageUrl+'/uploadFileImage'" :show-file-list="false"
                  :on-success="handleMasterSuccess" :before-upload="beforeAvatarUpload">
                  <el-image v-if="ruleForm.image" :src="$imagePath+ruleForm.image" class="avatar" width='100%;'
                    fit='cover' />
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
                <span class="form-word-hint">图片不能超过200KB，图片建议像素（或保持该比例）：宽720，高350</span>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="展示时间" prop="yxkjdate">
                <el-date-picker v-model="value1" type="datetimerange" range-separator="至" start-placeholder="开始日期"
                  end-placeholder="结束日期" value-format="yyyy-MM-dd HH:mm:ss" @change="selectTime">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="排序" prop="orderNo">
                <el-input-number v-model="ruleForm.orderNo" :min="0" :max="99" label=""></el-input-number>
                <span class="form-word-hint">序号越小越靠前显示 最大99</span>
              </el-form-item>
            </el-col>
          </el-form>
        </el-row>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm('ruleForm')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  import {
    fetchMBannerList,
    preBanner,
    deleteBanner,
    upBanner,
    downBanner,
    createIndexBanner,
    toUpdateIndexBanner,
    updateIndexBanner
  } from '@/api/mIndex'
  import {
    getCodeManager,
    codeToArray,
    uploadFileImage
  } from '@/api/all'
  import Pagination from '@/components/Pagination'
  import {
    Message
  } from 'element-ui'
  export default {
    name: 'mindexbannerlist',
    components: {
      Pagination
    },
    data() {
      return {
        dataList: [],
        floorStatus: [],
        total: 0,
        listLoading: true,
        listQuery: {
          page: 1,
          limit: 20,
          q_title: '',
          q_time: '',
          q_status: ''
        },
        currentRow: null,
        judgmentTitle: '移动端轮播图添加',
        judgmentType: '1',
        dialogFormVisible: false,
        value1: [],
        ruleForm: {
          title: "",
          orderNo: '',
          linkUrl: "",
          type: "",
          image: "",
          yxkjdate: ""
        },
        rules: {
          title: [{
              required: true,
              message: "请输入标题",
              trigger: "blur"
            },
            {
              max: 20,
              message: '不能超过20个字符',
              trigger: 'blur'
            }
          ],
          orderNo: [{
            required: true,
            message: "请输入排序号",
            trigger: "blur"
          }],
          linkUrl: [{
              required: true,
              message: "请输入链接地址",
              trigger: "blur"
            },
            {
              max: 50,
              message: '不能超过50个字符',
              trigger: 'blur'
            }
          ],
          image: [{
            required: true,
            message: "请上传图片",
            trigger: "change"
          }, ],
          yxkjdate: [{
            required: true,
            message: "请选择展示时间",
            trigger: "change"
          }, ]
        }

      }
    },
    created() {
      getCodeManager('USE_YN', () => {
        this.floorStatus = codeToArray('USE_YN');
      })
      this.getList()
    },
    methods: {
      handleCurrentChange(val) {
        // 选中当前行数据
        this.currentRow = val
      },
      // 获取列表数据
      getList() {
        this.listLoading = true
        fetchMBannerList(this.listQuery).then(response => {
          this.dataList = response.data.rows
          this.total = response.data.total
          this.listLoading = false
          console.log(this.dataList)
        })
      },
      handleFilter() {
        this.listQuery.page = 1
        this.getList()
      },
      check() {
        this.getList()
      },
      reset() {
        this.listQuery = {
          page: 1,
          limit: 20,
          q_name: '',
          q_time: '',
          q_status: ''
        }
        this.getList()
      },
      addBanner() {
        this.value1 = [];
        this.judgmentTitle = '移动端轮播图添加'
        this.judgmentType = '1'
        this.dialogFormVisible = true;
        this.resetForm('ruleForm')
      },
      editBanner() {
        if (!this.currentRow) {
          Message.error('请选择操作行。')
          return;
        };
        if (this.currentRow.status == 1) {
          Message.error('先停止使用，在进行修改。')
          return;
        }
        this.judgmentTitle = '移动端轮播图编辑'
        this.judgmentType = '2'
        this.dialogFormVisible = true;
        toUpdateIndexBanner({
          mIndexBannerId: this.currentRow.id
        }).then(res => {
          this.ruleForm = res.data.data.mIndexBanner;
          this.value1 = [];
          this.value1.push(this.ruleForm.startTime);
          this.value1.push(this.ruleForm.endTime);
          this.ruleForm.yxkjdate = this.ruleForm.startTime + " - " + this.ruleForm.endTime;
        })
      },
      del() {
        if (!this.currentRow) {
          Message.error('请选择操作行。')
          return;
        };
        if (this.currentRow.status == 1) {
          Message.error('使用中不能删除。')
          return;
        }
        this.$confirm('确定删除吗？', '提示', {
          onfirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteBanner({
            id: this.currentRow.id
          }).then(res => {
            if (res.data.success) {
              this.$message({
                type: 'success',
                message: '删除成功!'
              });
              this.getList()
            } else {
              this.$message({
                type: 'error',
                message: res.data.message
              });
            }
          })
        })
      },
      up() {
        if (!this.currentRow) {
          Message.error('请选择操作行。')
          return;
        };
        if (this.currentRow.status == 1) {
          Message.error('已经是启用状态，请勿重复操作。')
          return;
        }
        this.$confirm('确定启用吗？', '提示', {
          onfirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          upBanner({
            id: this.currentRow.id
          }).then(response => {
            if (!response.data.success) {
              Message.error(res.data.message);
              return;
            }
            Message.success('操作成功')
            this.getList()
          })
        })
      },
      down() {
        if (!this.currentRow) {
          Message.error('请选择操作行。')
          return;
        };
        if (this.currentRow.status == 0) {
          Message.error('已经是停用状态，请勿重复操作')
          return;
        }
        this.$confirm('确定停用吗？', '提示', {
          onfirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          downBanner({
            id: this.currentRow.id
          }).then(response => {
            if (!response.data.success) {
              Message.error(res.data.message);
              return;
            }
            Message.success('操作成功')
            this.getList()
          })
        })
      },
      preview() {
        window.open("http://bbch5.yixiekeji.com/previewindex.html");
      },
      handleMasterSuccess(res, file) {
        const formData = new FormData()
        formData.append('type', 'mbanner')
        formData.append('imageFile', file.raw)
        uploadFileImage(formData).then(result => {
          console.log(result)
          if (result.data.success) {
            this.ruleForm.image = result.data.data;
          }
        })
      },
      beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG和PNG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        return isJPG && isLt2M;
      },
      selectTime() {
        this.ruleForm.yxkjdate = this.value1[0] + " - " + this.value1[1];
      },
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            if (this.judgmentType == '1') {
              createIndexBanner(this.ruleForm).then(res => {
                console.log(res)
                if (!res.data.success) {
                  Message.error(res.data.message);
                  return;
                }
                Message.success('操作成功')
                this.resetForm('ruleForm')
                this.dialogFormVisible = false;
                this.getList()
              })
            } else {
              updateIndexBanner(this.ruleForm).then(res => {
                console.log(res)
                if (!res.data.success) {
                  Message.error(res.data.message);
                  return;
                }
                Message.success('操作成功')
                this.resetForm('ruleForm')
                this.dialogFormVisible = false;
                this.getList()
              })
            }
          }
        });
      },
      resetForm(formName) {
        this.$refs[formName].resetFields()
      }
    }
  }
</script>
<style scoped>
  .filter-container .el-col-6 {
    margin-bottom: 15px;
  }

  .filter-item {
    margin-bottom: 0
  }

  /deep/ .filter-container label {
    font-size: 14px;
    font-weight: 500;
    margin-right: 10px;
  }

  /deep/ .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  /deep/ .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  /deep/ [class*=el-col-] {
    float: none;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
  }

  .avatar {
    display: block;
    height: 150px;
  }
</style>
